//
//  QRCodeViewController.m
//  Hello
//
//  Created by Detailscool on 16/3/17.
//  Copyright © 2016年 Detailscool. All rights reserved.
//

#import "QRCodeViewController.h"
#import <AVFoundation/AVFoundation.h>

@interface QRCodeViewController ()<AVCaptureMetadataOutputObjectsDelegate>

@property (nonatomic,strong)AVCaptureSession * session;

@end

@implementation QRCodeViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.title = @"扫描商家";
    
    // 会话
    self.session = [[AVCaptureSession alloc]init];
    
    // 设备
    AVCaptureDevice * device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    
    // 输入
    AVCaptureDeviceInput * input = [AVCaptureDeviceInput deviceInputWithDevice:device error:nil];
    
    if ([self.session canAddInput:input]) {
        
        [self.session addInput:input];
        
    }
    
    // 输出
    AVCaptureMetadataOutput * output = [[AVCaptureMetadataOutput alloc]init];
    
    if ([self.session canAddOutput:output]) {
        
        [self.session addOutput:output];
    }
    
    [output setMetadataObjectsDelegate:self queue:dispatch_get_main_queue()];
    
    NSLog(@"%@",output.availableMetadataObjectTypes);
    
    output.metadataObjectTypes = @[@"org.iso.QRCode",@"org.iso.Code128",@"org.iso.Code39",@"org.gs1.EAN-13"];
    
    CGFloat width = AvailbleArea/self.view.bounds.size.width;
    CGFloat height = AvailbleArea/self.view.bounds.size.height;
    CGFloat x = (1 - width)*0.5;
    CGFloat y = (1 - height)*0.5;
    
    output.rectOfInterest = CGRectMake(y, x, height, width);
    
    [self.session startRunning];
    
    // 预览
    AVCaptureVideoPreviewLayer * previewLayer = [AVCaptureVideoPreviewLayer layerWithSession:self.session];
    previewLayer.frame = self.view.layer.bounds;
    [self.view.layer addSublayer:previewLayer];
    
    UIView * availbleAreaView = [[UIView alloc]init];
    availbleAreaView.backgroundColor = [UIColor clearColor];
    availbleAreaView.x = x * self.view.bounds.size.width;
    availbleAreaView.y = y * self.view.bounds.size.height;
    availbleAreaView.width = AvailbleArea;
    availbleAreaView.height = AvailbleArea;
    availbleAreaView.layer.borderWidth = 1;
    availbleAreaView.layer.borderColor = [UIColor greenColor].CGColor;
    [self.view addSubview:availbleAreaView];
}


// 扫描结果输出
- (void)captureOutput:(AVCaptureOutput *)captureOutput didOutputMetadataObjects:(NSArray *)metadataObjects fromConnection:(AVCaptureConnection *)connection {
    
    AVMetadataMachineReadableCodeObject * object = metadataObjects.lastObject;
    
    NSLog(@"%@",object.stringValue);
    
    
    [self.session stopRunning];
    
}


@end
